 /**
 * 代码组织：
 * 
 */

//some global var
var FEED_URL = "http://www.google.com/calendar/feeds/";
var gEventSource;
var calendarList = new Array();//放着calendar的名字组成的字符串
var calendarEntries = new Array();
var ownCalendarEntries = new Array(); //有owner权限的日历
var otherCalendarEntries = new Array(); //非owner权限的日历
var hashEntries = new Object();

google.load("gdata", "1");
google.setOnLoadCallback(init);


function login(){
    var token = google.accounts.user.login(FEED_URL);
    log("token after login:" + token);
}

function logout(){
    google.accounts.user.logout();
    init();
};

/**
 * hashEntries的存取器
 * 这个功能 后来写到eventCache里面了。不确定能否删掉，wait
 * @param {Object} calendarId
 */
function getCalendarById(calendarId)
{
	return hashEntries[calendarId];s
}

function getCalendarId(calendarEntry)
{//可以用generateCategoryId
	for (id in hashEntries)
	{
		if (hashEntries[id]==calendarEntry)
			return id;
	}
	return null;
}

function init(){
    log("init");
    google.gdata.client.init(handleError);
    var token = google.accounts.user.checkLogin(FEED_URL);
    myService = new google.gdata.calendar.CalendarService("TimeStamp-Services");
	log('init @ '+window.location.href);
	log('token: '+token);
    if (token) {//必然在ts.html里面
        initTimeline();
        getCalendars();
    }
    else {
		window.location.href = "login.html";
		return ;
    }
}

//reset the timeline
function reset(){
    gEventSource = [];
    initTimeline();
    hideCategoryCtl();
}


function getCalendars(){
    var calendarService = new google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');
    var feedURL = 'http://www.google.com/calendar/feeds/default/allcalendars/full';
    
    log("GET Calendar for :" + feedURL);
    var callback = function(result){
        var entries = result.feed.entry;
        calendarEntries = entries;
        //        calendarList = entries;
        calendarList = new Array();
        for (var i = 0; i < entries.length; i++) {
            var calendarEntry = entries[i];
			//modified by pengpai 2008.11.24
			if (calendarEntry.getAccessLevel().getValue() == "owner")
			{
				ownCalendarEntries.push(calendarEntry);
			}
			else
			{
				otherCalendarEntries.push(calendarEntry);	
			}
			//modified by pengpai 2008.11.25
			var categoryId = generateCategoryId(calendarEntry.getId().getValue());
			hashEntries[categoryId] = calendarEntry;
			
            var calendarTitle = calendarEntry.getTitle().getText();
            //      var color=getColor();
            log('Calendar title = ' + calendarTitle);
            var color = calendarEntry.getColor().getValue();
            log('Calendar color = ' + color);
            //      log (calendarEntry.getAlternateLink());
            log(calendarEntry.getContent().getText());
            log(calendarEntry.getAtomAlternateLink().getHref());
			//modified by pengpai, 2008.11.25
			//modified by ning @ 2008.12.17
            //getEvents(calendarEntry.getAtomAlternateLink().getHref(), color);
            //      debugger;
            calendarList.push(calendarEntry.getTitle().getText());
			//add by ning @2008-11-26
			Cache.Calendars.add(calendarEntry);
			
			
        }
        showCategoryCtl();
    }
    calendarService.getAllCalendarsFeed(feedURL, callback, handleError);
}

function getDefaultPrivateEvents(){
    var feed = 'http://www.google.com/calendar/feeds/default/private/full';//TODO: 多个feedURL不一样。
    //参数：singleevents  Indicates whether recurring events should be expanded or represented as a single event.  Valid values are true (expand recurring events) or false (leave recurring events represented as single events). Default is false.
    //TODO:用其他方式处理参数。
    getEvents(feed, 'blue');
}


//refact by ning @ 2008-11-26 
/**
 * 添加一个gEvent 数组到 timeline 
 * @param {Object} gEvent
 */

function addEventEntriesToTimeline(entries){
    var timelinerEntries = [];
	if (entries.length==0)
		return ;
	var ii = entries[0].getId().getValue();
	ii= Cache.Calendars.getCalendarOfEvent(ii).getId().getValue();//ii = calendar id 
	ii = generateCategoryId(ii)
	var color=Cache.Calendars.getById(ii).getColor().getValue();;
	
	
    for (var i = 0; i < entries.length; ++i) {
        var entry = entries[i];
        if (entry.getTimes().length == 0) 
            continue;//为周期性事件，没有这个参数。
        var when = entry.getTimes()[0];//对非周期事件。
        var start = when.getStartTime().getDate();
        var end = when.getEndTime().getDate();
        //			if ((start==null )||(end==null))
        //          	  debugger
        
        var title = entries[i].getTitle().getText();
        log("EVENT:" + title + start.toGMTString() + "  " + end.toGMTString());
        
        var content = entry.getContent().getText();
        var icon = undefined;
        var parm = {
            start: start,
            end: end,
            text: title,
            instant: start==end,
            content: content,
            icon: icon,
            color: color,
			id: entry.getId().getValue(),
        };
        timelinerEntries.push(new Timeline.DefaultEventSource.Event(parm));
    }
    gEventSource.addMany(timelinerEntries);
	if (entries.length>1)
	{
		var id = entries.length/2;
		id=Math.floor(id);
		log (id);
		start0= entries[id].getTimes()[0].getStartTime().getDate();
		tl.getBand(0).setCenterVisibleDate(start0);
	}

};

function loadGDataCallback(json){
    var entries = json.feed.getEntries();
	
	for (var i = 0; i < entries.length; ++i) {
		var entry = entries[i];
		Cache.Events.addEvent(entry);//唯一跟新Event Cache的地方。
	}
	
    addEventEntriesToTimeline(entries);
};
	
function getEvents(feedURL, color){
    feedURL += "?start-min=2008-08-16T00:00:00&start-max=2009-01-24T23:59:59&singleevents=true&orderby=starttime&sortorder=a&max-results=30";//1000浏览器崩溃。。
    log("GET Event for :" + feedURL);
    var calendarService = new google.gdata.calendar.CalendarService('ning-ning');
    //  debugger
    //login(feedURL);
	
    calendarService.getEventsFeed(feedURL, loadGDataCallback, handleError);
}


/**
 * 
 * @param {String} searchText
 */
function onSearch(searchText){

    var calendarService = new google.gdata.calendar.CalendarService('GoogleInc-jsguide-1.0');
	
	var cals= Cache.Calendars.getAllCalendars();
	for (var ii = 0; ii < cals.length; ii++) {
		feedUri = cals[ii].getAtomAlternateLink().getHref();
		// Full text query for this string
		var query = new google.gdata.calendar.CalendarEventQuery(feedUri);
		query.setFullTextQuery(searchText);
		gEventSource.clear();
		calendarService.getEventsFeed(query, loadGDataCallback, handleError);
	}
	
}

function handleError(e){
    if (e instanceof Error) {
        // Alert with the error line number, file and message.
        alert('Error at line ' + e.lineNumber +
        ' in ' +
        e.fileName +
        '\n' +
        'Message: ' +
        e.message);
        // If available, output HTTP error code and status text
        if (e.cause) {
            var errorStatus = e.cause.status;
            var statusText = e.cause.statusText;
            alert('Root cause: HTTP error ' + errorStatus + ' with status text of: ' +
            statusText);
        }
    }
    else {
        alert(e.toString());
    }
};
